<template>
    <Teleport to="body">
        <transition name="el-fade-in">
            <div class="download-dialog" v-if="visible">
                <div class="download-dialog__mask"></div>
                <div class="download-dialog__content">
                    <div class="top">
                        <el-icon class="is-loading" color="#333" size="22px">
                            <Loading />
                        </el-icon>
                        正在下载
                    </div>

                    <div class="progress">
                        <div
                            class="progress-bar"
                            :style="{ width: progress + '%' }"
                        ></div>
                    </div>
                </div>
            </div>
        </transition>
    </Teleport>
</template>
<script setup>
import { Loading } from "@element-plus/icons-vue";
import { DownloadFile } from "~/api";

const visible = ref(false);
const progress = ref(0);

const downloadFile = (name, url) => {
    DownloadFile(url, {
        onDownloadProgress: function (e) {
            const percentCompleted = Math.round((e.loaded * 100) / e.total);
            progress.value = percentCompleted;
        },
    })
        .then((blob) => {
            const a = document.createElement("a");
            const url = window.URL.createObjectURL(blob);
            a.href = url;
            a.download = name;
            a.click();
            window.URL.revokeObjectURL(url);
            visible.value = false;
            Message().success("下载成功!");
        })
        .catch((e) => {
            visible.value = false;
            Message().error("下载失败!");
        });
};

defineExpose({
    show(name, url) {
        progress.value = 0;
        visible.value = true;
        downloadFile(name, url);
    },
});
</script>
<style lang="scss" scoped>
.download-dialog {
    position: fixed;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vh;
    z-index: 999;

    &__mask {
        position: relative;
        width: 100%;
        height: 100%;
        background-color: rgba($color: #000000, $alpha: 0.5);
    }

    &__content {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 300px;
        height: 150px;
        background-color: #fff;
        transform: translate(-50%, -50%);
        border-radius: 10px;
    }

    .top {
        display: flex;
        justify-content: center;
        align-items: center;
        padding-top: 40px;
        font-size: 18px;

        :deep(.el-icon) {
            margin-right: 10px;
        }
    }

    .progress {
        width: 80%;
        height: 16px;
        border: 1px solid #5085fb;
        margin: 20px auto 0;
        border-radius: 10px;
        overflow: hidden;

        &-bar {
            width: 20%;
            height: 100%;
            background-color: #5085fb;
            transition: width 0.3s ease-in-out;
        }
    }
}
</style>
